const WXAPI = require('apifm-wxapi')
const imageUtil = require('../../utils/image')
const AUTH = require('../../utils/auth')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo:{
      avatarUrl:'',
      nickname:'',
      mobile:'',
    },
    url:'',
    code:'',
    mobileChnaged:false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.initData()
  },
initData(){
  this.getUserApiInfo()
  this.getLoginCode()
},
async   getLoginCode(){
  const code = await AUTH.wxaCode()
  this.setData({code})
  },
async getUserApiInfo() {
  const res = await WXAPI.userDetail()
  if (res.code === 0) {
    const userInfo = res.data.base
    this.setData({userInfo,url:userInfo.avatarUrl})
  }
},
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  async onSelectAvatar(res){
    const uploadRes =await  imageUtil.upload(res.detail.avatarUrl)
    let userInfo = this.data.userInfo
    userInfo.avatarUrl = uploadRes.url

    this.setData({userInfo,url:res.detail.avatarUrl})
  },
   onNicknameChange(res){
    const nickname = res.detail
    let userInfo = this.data.userInfo
    userInfo.nickname = nickname
    this.setData({userInfo})
   },
   onMobileChange(res){
    const mobile = res.detail
    let userInfo = this.data.userInfo
    userInfo.mobile = mobile
    this.setData({userInfo,mobileChnaged:true})
   },
   cancle(){
    wx.navigateBack()
   },
   async saveUserInfo(){

    const userInfo = this.data.userInfo
    const {avatarUrl,nickname} = userInfo
    const data = {avatarUrl,nickname}
    const res = await WXAPI.modifyUserInfo(data)
    if(res.code === 0){
      wx.navigateBack()
    }
   },
  async getMobile(e){
  
    if (!e.detail.errMsg || e.detail.errMsg != "getPhoneNumber:ok") {
      wx.showToast({
        title: "获取手机号失败",
        icon: 'none'
      })
      return;
    }
    const res = await WXAPI.bindMobileWxapp(this.data.code, e.detail.encryptedData, e.detail.iv)
    if (res.code === 10002) {
      wx.showToast({
        title: '请先登陆',
        icon: 'none'
      })
      return
    }
    if (res.code === 0) {
      wx.showToast({
        title: '成功',
        icon: 'success'
      })
      const userInfo = this.data.userInfo
      userInfo.mobile = res.data
      this.setData({
        userInfo
      })
    } else {
      wx.showToast({
        title: res.msg,
        icon: 'none'
      })
    }
  },
})